export default {
  namespaced: true,
  // 数据
  state: () => ({
    // 存放购物车商品的列表
    cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
  }),
  // 方法
  mutations: {
    // 加购物车的方法
    addToCart(state, goodsInfo) {
      // 查找购物车中是否有这个商品
      const findResults = state.cart.find((item) => item.goods_id === goodsInfo.goods_id)

      if (!findResults) {
        // 购物车中没有当前要加入的商品
        state.cart.push(goodsInfo)
      } else {
        // 购物车中已经有这个上了，只需要改变他的数量就可以
        findResults.goods_count++
      }
      this.commit('m_cart/savaStorage')
    },
    // 购物车的数据持久化
    savaStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    // 修改购物车中商品的状态
    updateState(state, goods) { // goods:{goods_id: 129, goods_state: false}
      const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
      if (findResult) {
        findResult.goods_state = goods.goods_state
        this.commit('m_cart/savaStorage')
      }
    },
    // 修改购物车中商品的数量
    updateNum(state, goods) { // goods: {goods_id: 47869, goods_count: 2}
      const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
      if (findResult) {
        findResult.goods_count = goods.goods_count
        this.commit('m_cart/savaStorage')
      }
    },
    // 根据id删除购物车中对应的商品
    removeGood(state, id) {
      state.cart = state.cart.filter((item) => item.goods_id !== id)
      this.commit('m_cart/savaStorage')
    },
    updateAllState(state,newState){
      state.cart.forEach(item=>item.goods_state=newState)
      this.commit('m_cart/savaStorage')
    }
  },
  // 计算属性
  getters: {
    total(state) {
      let t = 0
      state.cart.forEach((item) => t += item.goods_count)
      return t
    },
    checkedCount(state){
      return state.cart.filter(item=>item.goods_state).reduce((total,item)=>total+=item.goods_count,0)
    },
    computeAllGoodsPrice(state){
      return state.cart.filter(item=>item.goods_state).reduce((total,item)=>total+=item.goods_count*item.goods_price,0).toFixed(2)
    }
  }
}
